﻿using System;
using System.IO;
using System.Threading.Tasks;
using System.Windows;
using SkiaSharp;

namespace CardGenerator.ViewModel;

public static class SkiaBitmapExtensions
{
    public static SKBitmap RemoveEmptyBackgroundBounds(this SKBitmap sourceBitmap)
    {
        using (var bitmap = new SKBitmap(sourceBitmap.Width, sourceBitmap.Height, sourceBitmap.ColorType, sourceBitmap.AlphaType))
        {
            Func<Task> saver = async () =>
            {
                await File.WriteAllBytesAsync(@"C:\Users\Dream-Lab\Desktop\Template\temp\aa.jpg", bitmap.Encode(SKEncodedImageFormat.Jpeg, 100).ToArray());
            };
            sourceBitmap.ScalePixels(bitmap, SKFilterQuality.High);
            SKRect rect = SKRect.Empty;
            var pixels = bitmap.Pixels;
            for (var y = 0; y < bitmap.Height; y++)
            {
                Boolean _break = false;
                for (var x = 0; x < bitmap.Width; x++)
                {
                    var pixel = pixels[bitmap.Width * y + x];
                    var grayScale = (((0.299 * pixel.Red + 0.587 * pixel.Green + 0.114 * pixel.Blue) / 3) / 85) * (pixel.Alpha / 255);
                    if (grayScale < 0.9)
                    {
                        rect.Left = x;
                        rect.Top = y;
                        _break = true;
                        break;
                    }
                }

                if (_break) break;
            }

            for (var y = bitmap.Height - 1; y > 0; y--)
            {
                Boolean _break = false;
                for (var x = bitmap.Width - 1; x > 0; x--)
                {
                    var pixel = pixels[bitmap.Width * y + x];
                    var grayScale = (((0.299 * pixel.Red + 0.587 * pixel.Green + 0.114 * pixel.Blue) / 3) / 85) * (pixel.Alpha / 255);
                    if (grayScale < 0.9)
                    {
                        rect.Right = x;
                        rect.Bottom = y;
                        _break = true;
                        break;
                    }
                }

                if (_break) break;
            }

            var newBitmap = new SKBitmap((int) rect.Width + 10, (int) rect.Height + 10, bitmap.ColorType, bitmap.AlphaType);
            using (var canvas = new SKCanvas(newBitmap))
            {
                rect.Left -= 5;
                rect.Right += 5;
                rect.Top -= 5;
                rect.Bottom += 5;
                canvas.DrawBitmap(bitmap, rect, new SKRect(0, 0, newBitmap.Width, newBitmap.Height));
            }
            return newBitmap;
        }
    }
}
